<template>
	<view class="container">
		<view class="form-section">
			<view class="form-item">
				<text class="label">姓名</text>
				<input type="text" class="input" placeholder="请输入姓名" v-model="formData.name" @blur="validate('name')" />
				<text v-if="error.name" class="error">{{ error.name }}</text>
			</view>
			<view class="form-item">
				<text class="label">联系电话</text>
				<input type="tel" class="input" placeholder="请输入手机号码" v-model="formData.phone" @blur="validate('phone')" />
				<text v-if="error.phone" class="error">{{ error.phone }}</text>
			</view>
			<view class="form-item">
				<text class="label">备用联系方式</text>
				<input type="tel" class="input" placeholder="请输入备用手机号码" v-model="formData.backupContact"
					@blur="validate('backupContact')" />
				<text v-if="error.backupContact" class="error">{{ error.backupContact }}</text>
			</view>
			<view class="form-item">
				<text class="label">酒店地址</text>
				<input type="text" class="input" placeholder="请输入入住酒店地址" v-model="formData.hotelAddress"
					@blur="validate('hotelAddress')" />
				<text v-if="error.hotelAddress" class="error">{{ error.hotelAddress }}</text>
			</view>
		</view>
		
		<!-- 报名人数 -->
		<view class="form-section">
			<text class="section-title">报名人数</text>
			<view class="participant-row" v-for="(participant, index) in formData.participant" :key="index">
				<view class="participant-info">
					<text class="participant-label">{{ participant.label }}</text>
					<text class="participant-price">￥{{ participant.price }}</text>
				</view>
				<view class="counter">
					<button class="counter-btn minus" @click="decrement(index)" :disabled="isDecrementDisabled(index)">-</button>
					<text class="count">{{ participant.count }}</text>
					<button class="counter-btn plus" @click="increment(index)">+</button>
				</view>
			</view>
		</view>
		
		<!-- 旅游线路 -->
		<view class="form-section">
			<text class="section-title">旅游线路(可多选)</text>
			<view class="route-grid">
				<view class="route-item" v-for="(route, index) in availableRoutes" :key="route.id" @click="toggleRoute(route.id)">
					<image :src="route.imgUrl.split(' ')[0]" class="route-image" mode="aspectFill" />
					<view class="route-overlay"></view>
					<view class="route-info">
						<text class="route-label">{{ route.spotName }}</text>
						<text class="route-price">￥{{ route.adultFee }}起</text>
					</view>
					<uv-checkbox-group>
						<uv-checkbox 
							:customStyle="{
								position: 'absolute',
								top: '10rpx',
								right: '10rpx',
								zIndex: 2
							}" 
							shape="circle" 
							:checked="formData.selectedRoutes.includes(route.id)"
							@change="toggleRoute(route.id)"
						></uv-checkbox>
					</uv-checkbox-group>
				</view>
			</view>
		</view>
		
		<!-- 底部固定栏 -->
		<view class="footer-bar">
			<view class="total-price">
				<text>合计: </text>
				<text class="price">¥{{ formData.total }}</text>
			</view>
			<button class="submit-btn" @click="submit" :loading="isSubmitting">提交订单</button>
		</view>
	</view>
</template>

<script>
	import {
		getListAllAPI,
		submitTouristInfoAPI
	} from '/api/user.js';
	import {
		mapState
	} from 'pinia'
	import {
		useUserInfoStore
	} from '../../../stores/userInfo';
	import {
		isBindAgentAPI,
		bindUserAndAgentAPI,
		getOpenidByCodeAPI
	} from '../../../api/common.js';

	export default {
		data() {
			return {
				formData: {
					agentId: 'da68aca7469c8be1c29b5043c20e977b',
					userId: '',
					name: '',
					phone: '',
					backupContact: '',
					hotelAddress: '',
					participant: [{
							label: '成人',
							price: 0,
							count: 0
						},
						{
							label: '老人学生',
							price: 0,
							count: 0
						},
						{
							label: '儿童(一米三以下)',
							price: 0,
							count: 0
						}
					],
					selectedRoutes: [],
					total: 0
				},
				availableRoutes: [],
				error: {
					name: '',
					phone: '',
					backupContact: '',
					hotelAddress: ''
				},
				isSubmitting: false
			}
		},

		async onLoad(options) {
			this.getRoutesData();
		},

		watch: {
			'formData.selectedRoutes': {
				handler() {
					this.updateParticipantPrices();
					this.calculateTotal();
				},
				deep: true
			},
			'formData.participant': {
				handler() {
					this.calculateTotal();
				},
				deep: true
			}
		},

		computed: {
			...mapState(useUserInfoStore, ['userId']),
		},
		
		methods: {
			clearData() {
				for (let key in this.formData) {
					if (this.formData.hasOwnProperty(key)) {
						if (key === 'participant') {
							this.formData.participant.forEach(item => {
								item.price = 0
								item.count = 0
							})
						} else if (typeof this.formData[key] === 'number') {
							this.formData[key] = 0
						} else if (Array.isArray(this.formData[key])) {
							this.formData[key] = []
						} else {
							this.formData[key] = ''
						}
					}
				}
			},
			
			async getRoutesData() {
				try {
					uni.showLoading({ title: '加载中...' });
					const res = await getListAllAPI();
					this.availableRoutes = res.data;
				} catch (error) {
					console.error('获取线路数据失败:', error);
					uni.showToast({ title: '加载线路失败', icon: 'none' });
				} finally {
					uni.hideLoading();
				}
			},
			
			increment(index) {
				this.formData.participant[index].count++;
			},
			
			decrement(index) {
				if (this.formData.participant[index].count > 0) {
					this.formData.participant[index].count--;
				}
			},
			
			isDecrementDisabled(index) {
				return this.formData.participant[index].count === 0;
			},
			
			toggleRoute(routeId) {
				const index = this.formData.selectedRoutes.indexOf(routeId);
				if (index > -1) {
					this.formData.selectedRoutes.splice(index, 1);
				} else {
					this.formData.selectedRoutes.push(routeId);
				}
			},
			
			calculateTotal() {
				const participantTotal = this.formData.participant.reduce(
					(sum, participant) => sum + (participant.count * participant.price), 
					0
				);
				this.formData.total = participantTotal;
			},
			
			async submit() {
				if (!this.validateForm()) return;
				
				this.isSubmitting = true;
				try {
					this.formData.userId = this.userId;
					const res = await submitTouristInfoAPI(this.formData);
					
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
					
					setTimeout(() => {
						uni.switchTab({ url: '/common/pages/order/order' });
						this.clearData();
					}, 1500);
				} catch (err) {
					console.error('提交失败:', err);
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					});
				} finally {
					this.isSubmitting = false;
				}
			},
			
			updateParticipantPrices() {
				let adultFee = 0;
				let oldStuFee = 0;
				let childrenFee = 0;

				this.formData.selectedRoutes.forEach(routeId => {
					const route = this.availableRoutes.find(r => r.id === routeId);
					if (route) {
						adultFee += route.adultFee;
						oldStuFee += route.oldStuFee;
						childrenFee += route.childrenFee;
					}
				});

				this.formData.participant.forEach(participant => {
					switch (participant.label) {
						case '成人':
							participant.price = adultFee;
							break;
						case '老人学生':
							participant.price = oldStuFee;
							break;
						case '儿童(一米三以下)':
							participant.price = childrenFee;
							break;
					}
				});
			},
			
			validate(type) {
				const phoneRegex = /^1[0-9]{10}$/;
				
				switch(type) {
					case 'phone':
						this.error.phone = phoneRegex.test(this.formData.phone) ? '' : '请输入有效的手机号码';
						break;
					case 'backupContact':
						this.error.backupContact = phoneRegex.test(this.formData.backupContact) ? '' : '请输入有效的备用手机号码';
						break;
					case 'name':
						this.error.name = this.formData.name.trim() ? '' : '姓名不能为空';
						break;
					case 'hotelAddress':
						this.error.hotelAddress = this.formData.hotelAddress.trim() ? '' : '酒店地址不能为空';
						break;
				}
			},
			
			validateForm() {
				this.validate('name');
				this.validate('phone');
				this.validate('backupContact');
				this.validate('hotelAddress');
				
				const hasError = Object.values(this.error).some(msg => msg);
				const noParticipants = this.formData.participant.every(p => p.count === 0);
				const noRoutes = this.formData.selectedRoutes.length === 0;
				
				if (hasError) {
					uni.showToast({ title: '请检查表单填写', icon: 'none' });
					return false;
				}
				
				if (noParticipants) {
					uni.showToast({ title: '至少报名一位游客', icon: 'none' });
					return false;
				}
				
				if (noRoutes) {
					uni.showToast({ title: '至少选择一条旅游线路', icon: 'none' });
					return false;
				}
				
				return true;
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}
	
	.container {
		padding: 24rpx;
	}
	
	.form-section {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 24rpx;
		display: block;
	}
	
	.form-item {
		margin-bottom: 32rpx;
		position: relative;
		
		&:last-child {
			margin-bottom: 0;
		}
	}
	
	.label {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 12rpx;
		display: block;
	}
	
	.input {
		width: 100%;
		height: 80rpx;
		padding: 0 24rpx;
		border-radius: 8rpx;
		background-color: #f6f7fb;
		font-size: 28rpx;
		border: 1rpx solid #eee;
		box-sizing: border-box;
		
		&:focus {
			border-color: #007aff;
			background-color: #fff;
		}
	}
	
	.error {
		color: #ff4d4f;
		font-size: 24rpx;
		margin-top: 8rpx;
		display: block;
	}
	
	.participant-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		
		&:last-child {
			border-bottom: none;
		}
	}
	
	.participant-info {
		flex: 1;
	}
	
	.participant-label {
		font-size: 28rpx;
		color: #333;
	}
	
	.participant-price {
		font-size: 26rpx;
		color: #ff4d4f;
		margin-left: 16rpx;
	}
	
	.counter {
		display: flex;
		align-items: center;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		overflow: hidden;
	}
	
	.counter-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 36rpx;
		color: #666;
		background-color: #f5f5f5;
		border: none;
		padding: 0;
		margin: 0;
		
		&:after {
			border: none;
		}
		
		&.minus {
			color: #999;
		}
		
		&.plus {
			color: #007aff;
		}
		
		&[disabled] {
			opacity: 0.5;
		}
	}
	
	.count {
		width: 80rpx;
		height: 60rpx;
		text-align: center;
		line-height: 60rpx;
		font-size: 28rpx;
		color: #333;
		border-left: 1rpx solid #e0e0e0;
		border-right: 1rpx solid #e0e0e0;
	}
	
	.route-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
	}
	
	.route-item {
		position: relative;
		height: 240rpx;
		border-radius: 12rpx;
		overflow: hidden;
	}
	
	.route-image {
		width: 100%;
		height: 100%;
	}
	
	.route-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(to top, rgba(0,0,0,0.6), rgba(0,0,0,0.1));
	}
	
	.route-info {
		position: absolute;
		bottom: 20rpx;
		left: 20rpx;
		z-index: 1;
	}
	
	.route-label {
		font-size: 28rpx;
		color: #fff;
		font-weight: bold;
		display: block;
		margin-bottom: 8rpx;
	}
	
	.route-price {
		font-size: 24rpx;
		color: #fff;
	}
	
	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 24rpx;
		box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
	}
	
	.total-price {
		font-size: 28rpx;
		color: #333;
		
		.price {
			color: #ff4d4f;
			font-weight: bold;
			font-size: 32rpx;
		}
	}
	
	.submit-btn {
		width: 240rpx;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007aff;
		color: #fff;
		border-radius: 40rpx;
		font-size: 30rpx;
		border: none;
		
		&:after {
			border: none;
		}
		
		&[disabled] {
			background-color: #a0cfff;
		}
	}
</style>